<?php
 header("content-Type: text/html; charset=Utf-8");
define('TOKEN','111111');
// 接受xml数据
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
$postObj = simplexml_load_string($postStr,'SimpleXMLElement', LIBXML_NOCDATA );
if (!$postStr) {
    // echo "This is WechatApi !";
                $filepath = 'https://api.xiaohuwei.cn/qrcode/?text=';//文件的绝对路径
    $filedata = array (
            "media" =>new \CURLFile($filepath)
            );
     var_dump($filedata);
    // echo $_SERVER['DOCUMENT_ROOT'];
    exit;
}
function checkstr($str,$gui){
    $needle = $gui;//判断是否包含a这个字符
    $tmparray = explode($needle,$str);
    if(count($tmparray)>1){
    	//  $domain = strstr($str, $gui);
    	 return true;
    } else{
     return false;
    }
   }
function senMessage($postObj,$content){
    $toUser    =$postObj->FromUserName;
    $fromUser  =$postObj->ToUserName;
    $time      =time();
    $msgType   ='text';
    $content   = $content;
    $template="<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>";
    $info=sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
    echo $info;
}
//如果是关注 subscribe事件
if(strtolower($postObj->Event)=='subscribe')
{
    senMessage($postObj,"欢迎关注肖虎威工作室！\n回复菜单查看本公众号所有功能！😊");
}
$MsgType=$postObj->MsgType;
if($MsgType=='text'){
        $Content=$postObj->Content;
        if($Content=='菜单'){
            senMessage($postObj,"1.翻译功能。\n2.天气查询。\n回复相应的序号进入。");
        }else if($Content=='1' || $Content=='翻译'){
            senMessage($postObj,"回复 翻译+内容 \n例如 翻译你好世界！");
        }else if($Content=='2' || $Content=='天气' ){
            senMessage($postObj,"回复 城市+天气\n 例如 广州天气");
        }else if(checkstr($Content,'翻译')){
            $domain = substr(str_replace(" ","",$Content),4);
            $url="https://translate.testdiv.com/translate/index.php?text=".$domain;
            $file_content = file_get_contents($url);//返回标准的json
            $arr = (array) json_decode ($file_content);
            $res = $arr['data'];
            senMessage($postObj,str_replace("�","",$res));
        }else if(checkstr($Content,'天气')){
            $domain = substr(str_replace(" ","",$Content),0,6);
            $domain2 = str_replace("�","",$domain) ;
            $url = "https://api.xiaohuwei.cn/tianqi.php?city=".$domain2;
            $file_content = file_get_contents($url);//返回标准的json
            $arr = (array) json_decode ($file_content);
            $res = $arr['data'];
            senMessage($postObj,str_replace("�","",$res));
        }else if(checkstr($Content,'二维码')){
            $domain = substr(str_replace(" ","",$Content),9);
            $domain2 = str_replace("�","",$domain) ;
            $type = "image";
            $filepath = 'https://api.xiaohuwei.cn/qrcode/?text='.$domain2;//文件的绝对路径
            // $filedata = array (
            //   'filename'=>dirname(__FILE__)."/hb.jpg"; ,  //图片相对于网站根目录的路径
            // );
            $urls="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc78a249e4b6f224e&secret=46aa4fb857bd3f7f8ec03dc5cfbd72d1";
            $file_content = file_get_contents($urls);//返回标准的json
            $arr = (array) json_decode ($file_content);
            $access_token = $arr['access_token'];
            // $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$access_token."&type=".$type;
            //获取mediaID
            // $result = add_material($file_info,$access_token);   
             $params = [];
             
             // getAccessToken获取access_token的函数，如何获取查看官方文档
             $params['access_token'] = $access_token;
             $params['type'] = "image";
             $url = "https://api.weixin.qq.com/cgi-bin/media/upload";
             
             // 拼接后为 url?access_token=xxx&type=image
             $url = $url.'?'.http_build_query($params);
             
             // 相对于网站的图片的绝对路径
             $filename = "/hb.jpg";
             
             // 图片在服务器上的真是路径，如果是前端上传的，可以另行获取，这里使用的是网站上的图片作为测试
             $real_path = $_SERVER['DOCUMENT_ROOT'].$filename;
             
             // 图片data
             $file_data = array("media"=> new \CURLFile($real_path));
             
             // 发送请求
             $res = post($url, $file_data, false);
            // var_dump($result);
            senMessage($postObj,$res);
        }else{
            senMessage($postObj,"功能之外，暂不支持！\n如果您有任何疑问。\n请联系肖虎威👍\nhttps://blog.xiaohuwei.cn/");
        }
}else if($MsgType=='image'){
    $xml='	<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%d</CreateTime>
    <MsgType><![CDATA[image]]></MsgType>
    <Image>
    <MediaId><![CDATA[%s]]></MediaId>
    </Image>
    </xml>';
echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),$postObj->MediaId);
}


function post($url, $data = [], $json_encode=true) {
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    if ($data != null) {
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        // curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        if(gettype($data)==="string") {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        else {
            if ($json_encode) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
            } else {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $res = curl_exec($curl); // 执行操作
    curl_close($curl);

    $data = json_decode($res, true);
    if($data==NULL) {
        return $res;
    }
    else {
        return $data;
    }
}
